﻿using LS.DicomViewer.Common;
using LS.Screening.UI.Common;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;

namespace LS.DicomViewer.ViewModels
{
    public class DicomThumbnailViewModel : ViewModel
    {
        #region 属性/变量

        /// <summary>
        /// 影像路径
        /// </summary>
        [Reactive]
        public string DicomFilePath { get; set; }

        /// <summary>
        /// 位图
        /// </summary>
        [Reactive]
        public BitmapSource ImageSource { get; set; }

        /// <summary>
        /// 弹出Viewer
        /// </summary>
        public ReactiveCommand<Unit, Unit> ShowDicomViewerCommand { get; set; }

        public ReactiveCommand<Unit, Unit> Save { get; }

        #endregion 构造

        #region 构造

        public DicomThumbnailViewModel()
        {
            ShowDicomViewerCommand = ReactiveCommand.CreateFromTask(async unit => await ShowDicomViewer(), File.Exists(DicomFilePath));
        }

        #endregion

        #region 方法

        public async Task<DicomViewModel> ShowDicomViewer(bool showDrawToolbar = false, bool show3DButton = false, bool showPlayToolBar = false)
        {
            if (string.IsNullOrEmpty(DicomFilePath))
            {
                throw new Exception("Dicom文件在本地不存在，请检查");
            }
            return await Application.Current.MainWindow.Dispatcher.InvokeAsync(() =>
            {
                var view = new DicomViewer();
                var window = new Window();
                window.Content = view;
                window.Width = 1300;
                window.Height = 800;
                window.Style = (Style)Application.Current.Resources["WindowWin10"];
                //window.NonClientAreaBackground = new SolidColorBrush(Color.FromArgb(255, 2, 61, 74));
                window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                window.Owner = Application.Current.MainWindow;
                window.SizeToContent = SizeToContent.Manual;
                window.Title = System.IO.Path.GetFileName(DicomFilePath);
                window.ResizeMode = ResizeMode.CanResize;
                window.ShowInTaskbar = false;
                window.WindowStyle = WindowStyle.SingleBorderWindow;
                view.HorizontalAlignment = HorizontalAlignment.Stretch;
                view.VerticalAlignment = VerticalAlignment.Stretch;

                var vm = view.ViewModel;
                window.Loaded += async (a, b) =>
                {
                    vm.ShowDrawToolbar = showDrawToolbar;
                    vm.Show3DButton = show3DButton;
                    vm.ShowPlayToolbar = true;
                    await vm.Load(DicomFilePath);
                    view.drawCanvas.DrawingToolType = DrawTools.Tools.DrawToolType.Pointer;
                    //有时窗体内容不刷新，在此设置宽度让其刷新
                    window.Width = window.Width + 1;
                };
                window.KeyDown += (a, b) => window.Close();
                window.ShowDialog();
                return vm;
            });
        }

        /// <summary>
        /// 加载文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="frameTime"></param>
        /// <param name="pixelSpacing"></param>
        /// <returns></returns>
        public async Task Load(string path, double? frameTime, double? pixelSpacing)
        {
            if (string.IsNullOrEmpty(path))
            {
                DicomFilePath = null;
                ImageSource = null;
                return;
            }
            var t = typeof(DicomInfo);
            DicomFilePath = path;
            var dicomInfo = await DicomViewerHelper.SaveToCache(path, frameTime, pixelSpacing);//102
            var firstFile = Directory.GetFiles(dicomInfo.ImageFilesDir).FirstOrDefault();
            ImageSource = new BitmapImage(new Uri(firstFile));
        }

        public void Clear()
        {
            ImageSource = null;
            GC.Collect();
        }

        ~DicomThumbnailViewModel()
        {
            Clear();
        }

        #endregion 方法
    }
}